package org.erp.store.strategy.hook;

import org.erp.common.enums.DeviceInventoryEvent;
import org.erp.common.enums.ProductEvent;
import org.erp.store.domain.dto.BatchDeviceInventoryDto;
import org.erp.store.domain.dto.BatchStatusMqMessageDto;
import org.erp.store.domain.entity.DeviceInventory;
import org.erp.store.infrastructure.event.InventoryLogEvent;
import org.erp.store.infrastructure.mq.service.EventNotificationMqService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.IdUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Component("mqAndLogAfterPersistHook")
public class MqAndLogAfterPersistHook implements AfterPersistHook {
    @Resource
    private EventNotificationMqService eventNotificationMqService;

    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void accept(BatchDeviceInventoryDto dto, List<DeviceInventory> updateList, Map<String, Integer> originalStateMap) {
        List<Long> ids = updateList.stream().map(DeviceInventory::getId).collect(Collectors.toList());
        BatchStatusMqMessageDto mqDto = buildBatchStatusMqMessageDto(dto, ids);
        eventNotificationMqService.sendEventNotificationMessage(mqDto);
        eventPublisher.publishEvent(new InventoryLogEvent(updateList, dto.getTargetEvent(), originalStateMap));
    }

     private BatchStatusMqMessageDto buildBatchStatusMqMessageDto(BatchDeviceInventoryDto dto, List<Long> ids) {
        BatchStatusMqMessageDto mqDto = new BatchStatusMqMessageDto();
        mqDto.setStockIds(ids);
        mqDto.setUuid(IdUtil.fastUUID());
        mqDto.setOperateId(dto.getOperateId());
        mqDto.setOperateName(dto.getOperateName());
        mqDto.setEvent(dto.getTargetEvent());
        mqDto.setTransferId(dto.getTransferUserId());
        mqDto.setTransferName(dto.getTransferUserName());
        if (DeviceInventoryEvent.REJECT_TO_INBOUND == dto.getTargetEvent()) {
            mqDto.setProductEvent(ProductEvent.CONFIRM_OVERRULE);
        } else if (DeviceInventoryEvent.RETURN_TO_INBOUND == dto.getTargetEvent()) {
            mqDto.setProductEvent(ProductEvent.CONFIRM_RETURN);
        }
        return mqDto;
    }

    
}
